<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2020/5/12
 * Time: 9:34
 */

namespace App\Rpc\Traits\Service;

use App\Lib\Error\ErrorConstant;
use App\Lib\Error\Response;
use App\Rpc\Model\Dao\UserCarrierDao;
use App\Rpc\Model\Dao\UserConsignerDao;
use App\Rpc\Model\Dao\UserDao;
use App\Rpc\Model\Dao\UserDriverDao;
use Swoft\Bean\BeanFactory;
use App\Rpc\Validator\UserValidator;
use App\Rpc\Model\Logic\PermissionLogic;
use Swoft\Db\DB;
use Swoft\Validator\Exception\ValidatorException;
use App\Rpc\Validator\UserConsignerValidator;

/**
 * Class UserTtrait
 * @package App\Rpc\Traits
 */
trait UserTrait
{
    /**
     * 插入用户
     * @param array $data
     * @return array
     */
    public function userCreate(array $data): array
    {
        $diyValidator = [
            'UserValidator' => [ 'op' => 'add']
        ];
        try{
            /** @var UserDao $UserDao */
            $UserDao = BeanFactory::getBean(UserDao::class);

            $field = [
                'account' => '请输入租户人员账号',
                'password' => '请输入租户人员登录密码',
            ];

            //验证必须传输的参数
            $this->_requiredFields($field, $data);

            DB::beginTransaction();

            //添加item_id
            $data['item_id'] = create_item_id(uuid());
            //创建盐钥匙
            $data['salt'] = create_salt();
            //继续创建生成登录密码
            $data['password'] = create_password($data['password'], $data['salt']);
            //最后可以入库了,未冻结
            $data['frozen_state'] = $data['frozen_state']??0;
            //这里首先验证中间件
            validate($data, "UserValidator", [], $diyValidator);
            //@1入库
            $result = $UserDao->insert($data);

            if(!$result){
                throw new ValidatorException('创建租户成员失败');
            }

            //处理关系对应
            $role_user_data = [
                'permission_value' => $data['permission_value']??'tenant_admin',
                'user_id' => $result
            ];

            $this->_user_roles($role_user_data);

            //@4提交
            DB::commit();

            return Response::Info(['item_id' => $result]);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 用户更新
     * @param array $data
     * @return array
     */
    public function userUpdate(array $data): array
    {
        //验证数据是否合理更新
//        $diyValidator = [
//            'UserValidator' => [ 'op' => 'update']
//        ];
        try{
            //添加item_id
            $id = $data['item_id']??null;
            unset($data['item_id']);

            /** @var UserDao $UserDao */
            $UserDao = BeanFactory::getBean(UserDao::class);

            if(isset($data['password'])){
                //处理下密码
                $userInfo = $UserDao->getByWhere(['item_id' => $id], ['salt']);
                $data['password'] = create_password($data['password'], $userInfo['salt']??null);
            }

            $result = $UserDao->update($id, $data);

            return Response::Info(['state' => $result]);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 用户删除
     * @param array $data
     * @return array
     */
    public function userDelete(array $data): array
    {
        try{
            //添加item_id
            $id = $data['item_id']??null;
            unset($data['item_id']);

            /** @var UserDao $UserDao */
            $UserDao = BeanFactory::getBean(UserDao::class);
            $result = $UserDao->delete($id);

            return Response::Info(['state' => $result]);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 账号信息查询
     * @param array $data
     * @return array
     */
    public function userInfo(array $data): array
    {
        try{
            //添加item_id
            //根据item_id查询
            $id = $data['item_id']??null;
            unset($data['item_id']);
            $where['item_id'] = $id;
            /** @var UserDao $UserDao */
            $UserDao = BeanFactory::getBean(UserDao::class);
            $result = $UserDao->getByWhere($where);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 用户列表
     * @param array $data
     * @return array
     */
    public function userList(array $data): array
    {
        try {
            $condition = [
                'p' => $data['p']??1,
                'per' => $data['per']??10
            ];

            /** @var UserDao $UserDao */
            $UserDao = BeanFactory::getBean(UserDao::class);
            $result = $UserDao->getList($condition);
            if(!isset($result['data']) || !$result['data']){
                throw new ValidatorException('查询无果');
            }

            //查询结果
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }



    /**
     * 账号登录
     * @param array $data
     * @return array
     */
    public function userLogin(array $data): array
    {
        try {
            $account = $data['account']??null;
            $password = $data['password']??null;

            if(!$account || !$password){
                Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求参数错误');
            }
            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->userLogin($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
        //需要账号密码登录
        //account
        //password
    }

    /**
     * 用户退出登录
     * @param array $data
     * @return array
     */
    public function userLoginOut(array $data): array
    {
        try {
            $required = [
                'user_item_id' => '您暂无登录信息',
                'identity_id' => '您暂无登录信息',
            ];
            foreach ($required as $key => $require){
                if(!isset($data[$key]) || !$data[$key]){
                    throw new ValidatorException($require, 4002);
                }
            }

            //这里要做退出登录处理
            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->userLoginOut($data);
            if(!$result){
                throw new ValidatorException('操作失败', 4005);
            }
            return Response::Info(['state' => true]);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /**
     * 微信登录
     * @param array $data
     * @return array
     */
    public function wechatLogin(array $data): array
    {
        try {
            $required = [
                'tenant' => '请输入租户名称',
                'code' => '请输入code值',
                'iv' => '请输入iv',
                'phone' => '请输入手机号',
            ];

            foreach ($required as $key => $require) {
                if(!isset($data[$key]) || $data[$key] === ''){
                    throw new ValidatorException($require, 4002);
                }
            }

            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->wechatLogin($data);
            if($result['error_code'] <> 200){
                throw new ValidatorException($result['message']??'登陆失败', $result['error_code']??4003);
            }
            return Response::Info($result['result']);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
        //首先需要请求小程序登录接口
        //获取到openid进行账号绑定
        //登录信息查询
    }

    /**
     * @param array $data
     * @return array
     */
    public function userDriverIdCardToken(array $data): array
    {
        try {
            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            return $PermissionLogic->userDriverIdCardToken($data);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }

    /************************************************发送验证码******************************************************************/
    /**
     * 发送验证码
     * @param array $data
     * @return array
     */
    public function getCode(array $data): array
    {
        try {
            //手机号
            $phone = $data['phone']??'';
            //注册还是登录，1默认为注册 2登录 3修改支付密码 4修改登录密码
            $type  = $data['type']??1;
            //这里可以通过手机号验证是否需要进行发送
            if(empty($phone)){
                return Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '请求手机号错误');
            }
            if($type == 1){
                //代表是注册 需要去司机表查询是否已经注册
                $UserDriverDao = BeanFactory::getBean(UserDriverDao::class);
                $userData = $UserDriverDao->getByWhere(['account' => $phone]);
                if(!empty($userData)){
                    return Response::FatalError(ErrorConstant::VALIDATE_ERROR_CODE, '该手机号已注册，请直接登录');
                }
            }

            //如果手机号已经注册成功
            /** @var PermissionLogic $PermissionLogic */
            $PermissionLogic = BeanFactory::getBean(PermissionLogic::class);
            $result = $PermissionLogic->getCode($data);
            return Response::Info($result);
        }
        catch (\Exception $e){
            return Response::FatalError($e->getCode(), $e->getMessage());
        }
    }
    /************************************************end发送验证码****************************************************************/
}
